package service

/**
 * Author: ycliud
 * Description: 注册
 * Date:20250927
 */
import (
	"fmt"
	"kubernate-server/module"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type RegisterService struct {
}

type RegisterReq struct {
	UserID   string `json:"user_id" binding:"required"`
	Password string `json:"password" binding:"required"`
	Nickname string `json:"nickname" binding:"required"`
	db       *gorm.DB
}

type RegisterRsp struct {
	Message string `json:"message" binding:"required"`
}

func (*RegisterService) Register(ctx *gin.Context) {
	var req RegisterReq
	cmsApp := NewCmsApp()
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	// 密码加密
	/*hashedPassword, err := encryptPassword(req.Password)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{})
	}
	fmt.Println("hashedPassword", hashedPassword)*/

	ctx.ShouldBindJSON(&req)
	//
	fmt.Println(req.UserID)
	fmt.Println(req.Password)
	fmt.Println(req.Nickname)
	accountDao := NewAccountDao(cmsApp.db)
	// 账号校验（账号是否存在）

	isExist, err := accountDao.IsExist(req.UserID)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	if isExist {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "账号已存在"})
		return
	}
	// 账号信息持久化
	nowTime := time.Now()
	if err := accountDao.Create(module.Account{
		UserID:   req.UserID,
		Password: req.Password,
		Nickname: req.Nickname,
		Ct:       nowTime,
		Ut:       nowTime,
	}); err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    20000,
		"message": "ok",
		"data": &RegisterRsp{
			Message: fmt.Sprintf("注册成功"),
		},
	})
	fmt.Println("register end")
}

func encryptPassword(password string) (string, error) {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		fmt.Printf("bcrypt generate from password error  = %v", err)
		return "", err
	}
	return string(hashedPassword), err
}
